package com.ljx.rabbit.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ljx.rabbit.context.BaseContext;
import com.ljx.rabbit.domain.dto.AddCartDTO;
import com.ljx.rabbit.domain.po.Cart;
import com.ljx.rabbit.domain.po.Item;
import com.ljx.rabbit.domain.po.OrderGoods;
import com.ljx.rabbit.domain.po.Summary;
import com.ljx.rabbit.domain.vo.OrderSubmitVO;
import com.ljx.rabbit.domain.vo.SkuVo;
import com.ljx.rabbit.mapper.CartMapper;
import com.ljx.rabbit.mapper.ItemMapper;
import com.ljx.rabbit.service.IAddressService;
import com.ljx.rabbit.service.ICartService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.CrossOrigin;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author author
 * @since 2025-01-21
 */
@Service
@Slf4j
@RequiredArgsConstructor
@CrossOrigin
public class CartServiceImpl extends ServiceImpl<CartMapper, Cart> implements ICartService {
    private final ItemMapper itemMapper;
    private final IAddressService addressService;

    @Override
    @Transactional
    public void addCart(AddCartDTO addCartDTO) {
        // 插入到购物车，先判断购物车中该用户是否有该商品，如果有且shown为true，则修改数量，否则&&如果没有，则插入
        Long userId = BaseContext.getCurrentId();
        Cart cart1 = getOne(new QueryWrapper<Cart>().lambda().eq(Cart::getUserId, userId).eq(Cart::getSkuId, addCartDTO.getSkuId()).eq(Cart::isShown, true));
        if (cart1 != null) {
            log.info("购物车中已有该商品shown，修改数量 {}", cart1);
            Cart cart = cart1;
            cart.setCount(cart.getCount() + addCartDTO.getCount());
            updateById(cart);
            return;
        }
        List<Cart> ones = list(new QueryWrapper<Cart>().lambda().eq(Cart::getUserId, userId).eq(Cart::getSkuId, addCartDTO.getSkuId()).eq(Cart::isShown, false));
        Cart cart = new Cart();
        Long cartId = null;
        if (ones != null && ones.size() > 0) {
            log.info("购物车中已有该商品且不show，插入{}", ones);
            cartId = ones.get(ones.size() - 1).getId();

        }
        log.info("购物车中该商品不存在，插入");
        Long itemId = itemMapper.getItemIdBySkuId(addCartDTO.getSkuId());
        Item item = itemMapper.selectById(itemId);
        if (itemId == null) {
            log.error("商品不存在");
            throw new RuntimeException("商品不存在");
        }
        List<SkuVo> skuVos = itemMapper.getSkuVos(itemId);
        if (skuVos == null)
            throw new RuntimeException("商品类型不存在");
        String attrsText = "";

        for (SkuVo skuVo : skuVos) {
            if (skuVo.getSkuCode().equals(addCartDTO.getSkuId())) {
                attrsText = skuVo.getSpecs().toString().substring(1, skuVo.getSpecs().toString().length() - 1);
                cart.setPrice(skuVo.getPrice());
                BeanUtils.copyProperties(skuVo, cart);
                log.info("attrsText:{}", attrsText);
                break;
            }
        }

        cart.setUserId(userId);
        BeanUtils.copyProperties(addCartDTO, cart);
        cart.setItemId(itemId);
        cart.setAttrsText(attrsText);
        cart.setName(item.getName());
        cart.setSelected(addCartDTO.getSelected());
        if (cartId != null)
            cart.setId(cartId + 127);
        save(cart);
        log.info("cart:{}", cart);
    }

    @Override
    public void mergeCart(List<AddCartDTO> list) {
        for (AddCartDTO dto : list) {
//            QueryWrapper<Cart> wrapper = new QueryWrapper<>();
//            //不存在，直接添加
//            //存在shown 为true，修改数量，否则，shown为false
//            wrapper.lambda().eq(Cart::getUserId, BaseContext.getCurrentId()).eq(Cart::getSkuId, dto.getSkuId()).eq(Cart::isShown, true);
//            Cart cart = getOne(wrapper);
//            if (cart == null) {
//                log.info("该商品在购物车中不存在，直接添加");
//                addCart(dto);
//                continue;
//            }
//            cart.setCount(dto.getCount());
//            cart.setSelected(dto.getSelected());
//            updateById(cart);
            addCart(dto);
        }
    }

    @Override
    public OrderSubmitVO preOrder(Long id) {
        log.info("preOrder,id:{}",id);
        OrderSubmitVO orderSubmitVO = new OrderSubmitVO();
        orderSubmitVO.setUserAddresses(addressService.listAddress());
        List<Cart> carts = null;
        if (id == null) {
            QueryWrapper<Cart> wrapper = new QueryWrapper<>();
            wrapper.lambda()
                    .eq(Cart::getUserId, BaseContext.getCurrentId())
                    .eq(Cart::isSelected, true);
            carts = list(wrapper);
        } else {
            carts = list(new QueryWrapper<Cart>().lambda().eq(Cart::getOrderId, id));
        }
        if (carts == null || carts.size() == 0)
            throw new RuntimeException("请选择商品");
        List<OrderGoods> goods = new ArrayList<>();
        Integer goodsCount = 0;
        BigDecimal totalPrice = new BigDecimal(0);
        BigDecimal totalPayPrice = new BigDecimal(0);
        for (Cart cart : carts) {
            goodsCount += cart.getCount();
            OrderGoods orderGoods = new OrderGoods();
            orderGoods.setId(cart.getItemId());
            BeanUtils.copyProperties(cart, orderGoods);

            BigDecimal price = new BigDecimal(cart.getPrice());
            BigDecimal count = new BigDecimal(cart.getCount());
            BigDecimal multiply = price.multiply(count);
            orderGoods.setPayPrice(cart.getPrice());
            orderGoods.setTotalPrice(String.valueOf(multiply));
            totalPrice = multiply.add(totalPrice);
            totalPayPrice = multiply.add(totalPayPrice);
            orderGoods.setTotalPayPrice(String.valueOf(multiply));
            goods.add(orderGoods);
        }
        orderSubmitVO.setGoods(goods);
        Summary summary = new Summary();
        summary.setGoodsCount(goodsCount);
        summary.setTotalPrice(totalPrice);
        summary.setTotalPayPrice(totalPayPrice);
        orderSubmitVO.setSummary(summary);

        return orderSubmitVO;
    }

}
